<?php

$url = "http://wenwen.soso.com";
$html = file_get_contents($url);

$reg = '/<dt ch="ww.home.wtfl.one"><a href="\/z\/(c[0-9]*)\.htm">([\s\S^<]*)<\/a>[\s\S]*<\/dt>/iU';

preg_match_all($reg, $html, $data);


$cat = $data;


$smreg = '/<ul ch="ww.home.wtfl.two">[\s\S]*<li><a href="\/z\/(c[0-9]*)\.htm">([\s\S^<]*)<\/a><\/li><li><a href="\/z\/(c[0-9]*)\.htm">([\s\S^<]*)<\/a><\/li><li><a href="\/z\/(c[0-9]*)\.htm">([\s\S^<]*)<\/a><\/li>/iU';


preg_match_all($smreg, $html, $data2);


$hidecatreg = '/<ul ch="ww.home.wtfl.two">[\s\S^(<\/ul)]*<\/ul>/iU';

preg_match_all($hidecatreg, $html, $data3);


$result = "[";

$bigcat = array();


for ($i=0; $i < count($cat[1]); $i++) {


  $id = $cat[1][$i];
  $name= $cat[2][$i];

  $bigcat[$i]['id'] =  $id;
  $bigcat[$i]['name'] = $name; 

  $c =<<<EOC

  {
    "id":"$id",
    "name":"$name",
    "children": [
EOC;

$c .='{ "id":'. '"'.$data2[1][$i].'",';
$c .= '"name":'. '"'.$data2[2][$i].'"},';

$c .='{ "id":'. '"'.$data2[3][$i].'",';
$c .= ' "name":'. '"'.$data2[4][$i].'"},';


$hidemenu = $data3[0][$i];

$li = '/<li><a href="\/z\/(c[0-9]*)\.htm">([\s\S^<]*)<\/a><\/li>/iU';

preg_match_all($li, $hidemenu, $data4);

for ($j = 0; $j<count($data4[0]); $j++) {
//  $bigcat[$i]->children[$j] = 
    $tmp = "{";
    $tmp .= '"id":"'.$data4[1][$j]. '",';
    $tmp .= '"name":"'.$data4[2][$j]. '"';
    $tmp  .= "},";
    $c .= $tmp;
}



$c .='{ "id":'. '"'.$data2[5][$i].'",';
$c .= ' "name":'. '"'.$data2[6][$i].'"}';



$c .= ']';
if ($i == count($cat[1])-1) 
    $c .= "}";
else 
    $c .= "},";
  $result .= $c;


}
$result .= "]";


$categories = json_decode($result); 

foreach ($categories as $cat) {
  echo '<div class="category-box"><h3><a href="/category/'.$cat->id.'.html">'.$cat->name.'</a></h3>';
  echo '<ul class="subcats">';
  foreach ($cat->children as $subcat) {
    echo '<li><a href="/category/'.$subcat->id.'.html">'.$subcat->name."</a></li>"; 
  }
  echo '</ul>';

  echo "</div>";

}

